package com.learn.hibernatevalidator.chapter09;

import org.hibernate.validator.spi.scripting.AbstractCachingScriptEvaluatorFactory;
import org.hibernate.validator.spi.scripting.ScriptEngineScriptEvaluator;
import org.hibernate.validator.spi.scripting.ScriptEvaluationException;
import org.hibernate.validator.spi.scripting.ScriptEvaluator;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * @author: liyf
 * @create: 2025-01-21 20:56
 **/
public class MultiClassLoaderScriptEvaluatorFactory extends AbstractCachingScriptEvaluatorFactory {

    private final ClassLoader[] classLoaders;

    public MultiClassLoaderScriptEvaluatorFactory(ClassLoader... classLoaders) {
        if (classLoaders.length == 0) {
            throw new IllegalArgumentException("No class loaders were passed");
        }
        this.classLoaders = classLoaders;
    }

    @Override
    protected ScriptEvaluator createNewScriptEvaluator(String languageName) {
        for (ClassLoader classLoader : classLoaders) {
            ScriptEngine engine = new ScriptEngineManager(classLoader).getEngineByName(languageName);
            if (engine != null) {
                return new ScriptEngineScriptEvaluator(engine);
            }
        }
        throw new ScriptEvaluationException("No JSR 223 script engine found for language " + languageName);
    }
}
